package com.bto.solar.work.controller;

import com.alibaba.fastjson2.JSONObject;
import com.bto.solar.work.common.R;
import com.bto.solar.work.constant.BizStageEnum;
import com.bto.solar.work.constant.BizTaskEnum;
import com.bto.solar.work.constant.BizTaskStateEnum;
import com.bto.solar.work.dao.IAppointService;
import com.bto.solar.work.entity.Appoint;
import com.bto.solar.work.service.BtoOperateLogService;
import com.bto.solar.work.service.biz_stage_handler.KanChaStageHandler;
import com.bto.solar.work.utils.NullUtils;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 指派 前端控制器
 * </p>
 *
 * @author adrian
 * @since 2023-08-09
 */
@RestController
@RequestMapping("/appoint")
public class AppointController {
    @Autowired
    private IAppointService appointService;
    @Autowired
    @Lazy
    private KanChaStageHandler kanChaStageHandler;
    @Autowired
    private BtoOperateLogService optLog;

    @ApiModelProperty("技术勘察委派")
    @PostMapping("jskc")
    public R downloadExcelOrderInfo(@RequestParam String orderId , @RequestParam Long userId)  {
        Appoint appoint = appointService.lambdaQuery()
                .eq(Appoint::getOrderId, orderId)
                .eq(Appoint::getStageId, BizStageEnum.KAN_CHA.getStageId())
                .eq(Appoint::getTaskId , BizTaskEnum.TASK_JSKC.getTaskId())
                .eq(Appoint::getStateId, BizTaskStateEnum.WAITING_APPOINT.getStateId())
                .one();
        if(NullUtils.isNull(appoint)){
            appoint = new Appoint();
            appoint.setOrderId(orderId);
            appoint.setStageId(BizStageEnum.KAN_CHA.getStageId());
            appoint.setTaskId(BizTaskEnum.TASK_JSKC.getTaskId());
            appoint.setStateId(BizTaskStateEnum.WAITING_APPOINT.getStateId());
        }
        appoint.setUserId(userId);
        boolean saveOrUpdate = appointService.saveOrUpdate(appoint);
        if(saveOrUpdate){
            optLog.setOperatInfo(JSONObject.from(appoint));
            kanChaStageHandler.updateWaitingAppointToFilled(orderId);
        }

        return saveOrUpdate ? R.ok() : R.fail();
    }
}
